package com.prestamomo.vil.ppa.pmvilmedium.pmvilarm.pmnet;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.prestamomo.vil.ppa.PmvilApp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class PmvilNetInfoMd {

    public static JSONObject getInfoPmvilNet() {
        JSONObject netPmvilWokObj = new JSONObject();
        Map<String,Object> pmvilNetMap = new HashMap<>();
        try {
            pmvilNetMap.put("pmvilsew","kilws");
            netPmvilWokObj.put("xctwslglx", getPmvilDqWifi(PmvilApp.getPmvilApss()));//--current_wifi
            netPmvilWokObj.put("daist", TextUtils.isEmpty(getIpPmvilAddress(PmvilApp.getPmvilApss())) ? "" : getIpPmvilAddress(PmvilApp.getPmvilApss()));//ip--IP
            WifiManager wifiPmvilManager = (WifiManager) PmvilApp.getPmvilApss().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            @SuppressLint("MissingPermission") List<ScanResult> allPmvilWifiDetails = wifiPmvilManager.getScanResults();
            netPmvilWokObj.put("wpdnzbql", allPmvilWifiDetails != null ? allPmvilWifiDetails.size() : 0);//--wifi_count
            netPmvilWokObj.put("txkeoqox", getPmvilAllWifi(allPmvilWifiDetails));//--configured_wifi
        } catch (Exception e) {
            e.printStackTrace();
            pmvilNetMap.put("pmvilsew","mislw");
        } finally {
            if(pmvilNetMap.size()!=0){
                pmvilNetMap.clear();
            }
        }
        return netPmvilWokObj;
    }


    private static JSONArray getPmvilAllWifi(List<ScanResult> allWifiPmvilDetails) throws JSONException {
        JSONArray allPmvilWifi = new JSONArray();
        for (int i = 0; i < allWifiPmvilDetails.size(); i++) {
            JSONObject wifiPmvilObj = new JSONObject();
            wifiPmvilObj.put("ifnarr", !TextUtils.isEmpty(allWifiPmvilDetails.get(i).BSSID) ? allWifiPmvilDetails.get(i).BSSID.replace("%", "-").replace("\"", "") : "");//wifi BSSID--bssid
            wifiPmvilObj.put("vietzfsk", TextUtils.isEmpty(allWifiPmvilDetails.get(i).SSID) ? "" : allWifiPmvilDetails.get(i).SSID.replace("%", "-").replace("\"", ""));//--name
            wifiPmvilObj.put("bkfci", TextUtils.isEmpty(allWifiPmvilDetails.get(i).SSID) ? "" : allWifiPmvilDetails.get(i).SSID.replace("%", "-").replace("\"", ""));//--ssid
            wifiPmvilObj.put("hhpfkib", getMacPmvilAddress(PmvilApp.getPmvilApss()).replace("\"", ""));//wifi mac--mac
            allPmvilWifi.put(wifiPmvilObj);
        }
        return allPmvilWifi;
    }


    private static WifiInfo getConnectedPmvilWifi(Context pmvilCext) {
        Map<String,Object> pmvilOlswifi = new HashMap<>();
        try {
            pmvilOlswifi.put("pmvilswifi",true);
            WifiManager wifiPmvilManager = (WifiManager) pmvilCext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            return wifiPmvilManager == null ? null : wifiPmvilManager.getConnectionInfo();
        } catch (Exception e) {
            pmvilOlswifi.put("pmvilswifi",false);
            return null;
        }finally {
            if(pmvilOlswifi.size()!=0){
                pmvilOlswifi.clear();
            }
        }
    }

    private static JSONObject getPmvilDqWifi(Context pmvilCtext)  {
        JSONObject wifiPmvilObj = new JSONObject();
        Map<String,Object> pmvilOlsewfi = new HashMap<>();
        try {
            pmvilOlsewfi.put("lsiwPmvil","kinwl");
            WifiInfo connectedWifiInfo = getConnectedPmvilWifi(pmvilCtext);
            wifiPmvilObj.put("ifnarr", connectedWifiInfo == null ? "" : connectedWifiInfo.getBSSID());//wifi BSSID--bssid
            wifiPmvilObj.put("vietzfsk", connectedWifiInfo == null ? "" : connectedWifiInfo.getSSID().replace("\"", ""));//--name
            wifiPmvilObj.put("bkfci", connectedWifiInfo == null ? "" : connectedWifiInfo.getSSID().replace("\"", ""));//--ssid
            wifiPmvilObj.put("hhpfkib", getMacPmvilAddress(PmvilApp.getPmvilApss()));//wifi mac--mac
        }catch (Exception e){
            pmvilOlsewfi.put("lsiwPmvil","pmilws");
        }finally {
            if(pmvilOlsewfi.size()!=0){
                pmvilOlsewfi.clear();
            }
        }

        return wifiPmvilObj;
    }

    public static String getMacPmvilAddress(@NonNull Context pmvilCxt) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                return getMacPmvilAddress();
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return getMacPmvilFromHardware();
            }
        } else {
            return getWifiPmvilMac(pmvilCxt);
        }
        return "02:00:00:00:00:00";
    }


    @SuppressLint("MissingPermission")
    private static String getWifiPmvilMac(@NonNull Context pmvilCot) {
        try {
            WifiManager wifiManager = (WifiManager) pmvilCot.getSystemService(Context.WIFI_SERVICE);
            return wifiManager.getConnectionInfo().getMacAddress();
        } catch (Exception e) {
            return "02:00:00:00:00:00";
        }
    }


    private static String getMacPmvilAddress() {
        Map<String,Object> pmvilMacPs = new HashMap<>();
        try {
            pmvilMacPs.put("pmvilSw",true);
            return new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
        } catch (IOException e) {
            e.printStackTrace();
            pmvilMacPs.put("pmvils","iwwl");
            return "02:00:00:00:00:00";
        }finally {
            if(pmvilMacPs.size()!=0) pmvilMacPs.clear();
        }
    }


    private static String getMacPmvilFromHardware() {
        String pmvilMac = "02:00:00:00:00:00";
        try {
            List<NetworkInterface> pmvilAll = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (int i = 0; i < pmvilAll.size(); i++) {
                if (!pmvilAll.get(i).getName().equalsIgnoreCase("wlan0")) continue;
                if (pmvilAll.get(i).getHardwareAddress() == null) {
                    return null;
                } else {
                    StringBuilder res1 = new StringBuilder();
                    for (byte b : pmvilAll.get(i).getHardwareAddress()) {
                        res1.append(String.format("%02X:", b));
                    }
                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                        pmvilMac = res1.toString();
                    }
                    return pmvilMac;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return pmvilMac;
    }

    private static String getIpPmvilAddress(Context pmvilCt) {
        if (isConnectedPmvilToWifi(pmvilCt)) {
            return getWifiIpPmvilAddress(pmvilCt);
        } else if (isContedPmvilToMobileData(pmvilCt)) {// --getMobileDataIPAddress
            try {
                List<NetworkInterface> networkPmvilIntefaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (int i = 0; i < networkPmvilIntefaces.size(); i++) {
                    NetworkInterface networkPmvilInterface = networkPmvilIntefaces.get(i);
                    for (int j = 0; j < Collections.list(networkPmvilInterface.getInetAddresses()).size(); j++) {
                        InetAddress inetPmvilAddress = Collections.list(networkPmvilInterface.getInetAddresses()).get(j);
                        if (!inetPmvilAddress.isLoopbackAddress()) {
                            String pmvilAddress = inetPmvilAddress.getHostAddress();
                            if (pmvilAddress.contains("%")) {
                                if (pmvilAddress.indexOf('%') >= 0) {
                                    return pmvilAddress.substring(0, pmvilAddress.indexOf('%'));
                                } else {
                                    return null;
                                }
                            } else {
                                return pmvilAddress;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            return null;
        } else {
            return null;
        }
    }


    private static boolean isConnectedPmvilToWifi(Context pmvilCtext) {
        ConnectivityManager connectyPmvilManager = (ConnectivityManager) pmvilCtext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectyPmvilManager != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return connectyPmvilManager.getActiveNetwork() == null ? false : connectyPmvilManager.getNetworkCapabilities(connectyPmvilManager.getActiveNetwork()) != null && connectyPmvilManager.getNetworkCapabilities(connectyPmvilManager.getActiveNetwork()).hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
            } else {
                NetworkInfo networkPmvilInfo = connectyPmvilManager.getActiveNetworkInfo();
                return networkPmvilInfo != null && networkPmvilInfo.getType() == ConnectivityManager.TYPE_WIFI;
            }
        } else {
            return false;
        }
    }


    private static boolean isContedPmvilToMobileData(Context PmvilCext) {
        if ((ConnectivityManager) PmvilCext.getSystemService(Context.CONNECTIVITY_SERVICE) != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Network netPmvilWork = ((ConnectivityManager) PmvilCext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetwork();
                return inopPmvilILs(PmvilCext, netPmvilWork);
            } else {
                NetworkInfo networkPmvilInfo = ((ConnectivityManager) PmvilCext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
                return networkPmvilInfo != null && networkPmvilInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            }
        } else {
            return false;
        }
    }

    private static boolean inopPmvilILs(Context PmvilCext, Network netPmvilWork) {
        if (netPmvilWork != null) {
            NetworkCapabilities networkPmvilCapaies = ((ConnectivityManager) PmvilCext.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkCapabilities(netPmvilWork);
            return networkPmvilCapaies != null && networkPmvilCapaies.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
        } else {
            return false;
        }
    }


    private static String getWifiIpPmvilAddress(Context pmvilCtext) {
        if (((WifiManager) pmvilCtext.getApplicationContext().getSystemService(Context.WIFI_SERVICE)) != null) {
            int ipPmvilAddress = ((WifiManager) pmvilCtext.getApplicationContext().getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getIpAddress();
            return (ipPmvilAddress & 0xFF) + "." + ((ipPmvilAddress >> 8) & 0xFF) + "." + ((ipPmvilAddress >> 16) & 0xFF) + "." + (ipPmvilAddress >> 24 & 0xFF);
        } else {
            return null;
        }
    }
}
